
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>JavaScript奇技淫巧44招 - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,原文地址

首次为变量赋值时务必使用var关键字变量没有声明而直接赋值得话，默认会作为一个新的全局变量，要尽量避免使用全局变量。
使用===取代====和!=操作符会在需要的情况下自动转换数据类型。,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">JavaScript奇技淫巧44招</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="/categories/Js"><b>「
                    </b>JS<b> 」</b></a>
                
                February 27, 2018
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2018/02/27/Js/JavaScript%E5%A5%87%E6%8A%80%E6%B7%AB%E5%B7%A745%E6%8B%9B/" title="JavaScript奇技淫巧44招" class="">JavaScript奇技淫巧44招</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    49k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    45 mins.
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/Js/" rel="tag">Js</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <p><a href="http://chensd.com/2015-01/45-useful-javascript-tips-tricks-and-best-practices.html" target="_blank" rel="noopener">原文地址</a></p>
<hr>
<h1 id="首次为变量赋值时务必使用var关键字"><a href="#首次为变量赋值时务必使用var关键字" class="headerlink" title="首次为变量赋值时务必使用var关键字"></a>首次为变量赋值时务必使用var关键字</h1><p>变量没有声明而直接赋值得话，默认会作为一个新的全局变量，要尽量避免使用全局变量。</p>
<h1 id="使用-取代"><a href="#使用-取代" class="headerlink" title="使用===取代=="></a>使用<strong>===</strong>取代<strong>==</strong></h1><p>==和!=操作符会在需要的情况下自动转换数据类型。但===和!==不会，它们会同时比较值和数据类型，这也使得它们要比==和!=快。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">10</span>] === <span class="number">10</span>    <span class="comment">// is false</span></span><br><span class="line">[<span class="number">10</span>]  == <span class="number">10</span>    <span class="comment">// is true</span></span><br><span class="line"><span class="string">'10'</span> == <span class="number">10</span>     <span class="comment">// is true</span></span><br><span class="line"><span class="string">'10'</span> === <span class="number">10</span>    <span class="comment">// is false</span></span><br><span class="line"> []   == <span class="number">0</span>     <span class="comment">// is true</span></span><br><span class="line"> [] ===  <span class="number">0</span>     <span class="comment">// is false</span></span><br><span class="line"> <span class="string">''</span> == <span class="literal">false</span>   <span class="comment">// is true but true == "a" is false</span></span><br><span class="line"> <span class="string">''</span> === <span class="literal">false</span>  <span class="comment">// is false</span></span><br></pre></td></tr></table></figure>
<h1 id="underfined、null、0、false、NaN、空字符串的逻辑结果均为false"><a href="#underfined、null、0、false、NaN、空字符串的逻辑结果均为false" class="headerlink" title="underfined、null、0、false、NaN、空字符串的逻辑结果均为false"></a>underfined、null、0、false、NaN、空字符串的逻辑结果均为false</h1><h1 id="行尾使用分号"><a href="#行尾使用分号" class="headerlink" title="行尾使用分号"></a>行尾使用分号</h1><p>实践中最好还是使用分号，忘了写也没事，大部分情况下JavaScript解释器都会自动添加。对于为何要使用分号，可参考文章<a href="https://davidwalsh.name/javascript-semicolons" target="_blank" rel="noopener">JavaScript中关于分号的真相</a><br><a id="more"></a></p>
<h1 id="使用对象构造器"><a href="#使用对象构造器" class="headerlink" title="使用对象构造器"></a>使用对象构造器</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">firstName, lastName</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.firstName =  firstName;</span><br><span class="line">    <span class="keyword">this</span>.lastName = lastName;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> Saad = <span class="keyword">new</span> Person(<span class="string">"Saad"</span>, <span class="string">"Mousliki"</span>);</span><br></pre></td></tr></table></figure>
<h1 id="小心使用typeof、instanceof和contructor"><a href="#小心使用typeof、instanceof和contructor" class="headerlink" title="小心使用typeof、instanceof和contructor"></a>小心使用typeof、instanceof和contructor</h1><blockquote>
<ul>
<li>typeof：JavaScript一元操作符，用于以字符串的形式返回变量的原始类型，注意，typeof null也会返回object，大多数的对象类型（数组Array、时间Date等）也会返回object</li>
<li>contructor：内部原型属性，可以通过代码重写</li>
<li>instanceof：JavaScript操作符，会在原型链中的构造器中搜索，找到则返回true，否则返回false</li>
</ul>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>];</span><br><span class="line"><span class="keyword">typeof</span> arr;   <span class="comment">// 返回 "object" </span></span><br><span class="line">arr <span class="keyword">instanceof</span> <span class="built_in">Array</span> <span class="comment">// true</span></span><br><span class="line">arr.constructor();  <span class="comment">//[]</span></span><br></pre></td></tr></table></figure>
<h1 id="使用自调用函数"><a href="#使用自调用函数" class="headerlink" title="使用自调用函数"></a>使用自调用函数</h1><p>函数在创建之后直接自动执行，通常称之为自调用匿名函数（Self-Invoked Anonymous Function）或直接调用函数表达式（Immediately Invoked Function Expression ）。格式如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 置于此处的代码将自动执行</span></span><br><span class="line">&#125;)(); </span><br><span class="line"></span><br><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params">a,b</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> result = a+b;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;)(<span class="number">10</span>,<span class="number">20</span>)</span><br></pre></td></tr></table></figure>
<h1 id="从数组中随机获取成员"><a href="#从数组中随机获取成员" class="headerlink" title="从数组中随机获取成员"></a>从数组中随机获取成员</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> items = [<span class="number">12</span>, <span class="number">548</span> , <span class="string">'a'</span> , <span class="number">2</span> , <span class="number">5478</span> , <span class="string">'foo'</span> , <span class="number">8852</span>, , <span class="string">'Doe'</span> , <span class="number">2145</span> , <span class="number">119</span>];</span><br><span class="line"><span class="keyword">var</span>  randomItem = items[<span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * items.length)];</span><br><span class="line"><span class="built_in">console</span>.log(randomItem);</span><br></pre></td></tr></table></figure>
<h1 id="获取指定范围内的随机数"><a href="#获取指定范围内的随机数" class="headerlink" title="获取指定范围内的随机数"></a>获取指定范围内的随机数</h1><p>这个功能在生成测试用的假数据时特别有数，比如介与指定范围内的工资数。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x = <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * (max - min + <span class="number">1</span>)) + min;</span><br></pre></td></tr></table></figure></p>
<h1 id="生成从0到指定值的数字数组"><a href="#生成从0到指定值的数字数组" class="headerlink" title="生成从0到指定值的数字数组"></a>生成从0到指定值的数字数组</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> numbersArray = [] , max = <span class="number">100</span>;</span><br><span class="line"><span class="keyword">for</span>( <span class="keyword">var</span> i=<span class="number">1</span>; numbersArray.push(i++) &lt; max;);  <span class="comment">// numbers = [1,2,3 ... 100]</span></span><br></pre></td></tr></table></figure>
<h1 id="生成随机的字母数字字符串"><a href="#生成随机的字母数字字符串" class="headerlink" title="生成随机的字母数字字符串"></a>生成随机的字母数字字符串</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">generateRandomAlphaNum</span>(<span class="params">len</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> rdmString = <span class="string">""</span>;</span><br><span class="line">    <span class="keyword">for</span>( ; rdmString.length &lt; len; rdmString  += <span class="built_in">Math</span>.random().toString(<span class="number">36</span>).substr(<span class="number">2</span>));</span><br><span class="line">    <span class="keyword">return</span>  rdmString.substr(<span class="number">0</span>, len);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="打乱数字数组的顺序"><a href="#打乱数字数组的顺序" class="headerlink" title="打乱数字数组的顺序"></a>打乱数字数组的顺序</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> numbers = [<span class="number">5</span>, <span class="number">458</span> , <span class="number">120</span> , <span class="number">-215</span> , <span class="number">228</span> , <span class="number">400</span> , <span class="number">122205</span>, <span class="number">-85411</span>];</span><br><span class="line">numbers = numbers.sort(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123; <span class="keyword">return</span> <span class="built_in">Math</span>.random() - <span class="number">0.5</span>&#125;);</span><br><span class="line"><span class="comment">/* numbers 数组将类似于 [120, 5, 228, -215, 400, 458, -85411, 122205]  */</span></span><br></pre></td></tr></table></figure>
<p>这里使用了JavaScript内置的数组排序函数，更好的办法是用专门的代码来实现（如Fisher-Yates算法</p>
<h1 id="字符串去空格"><a href="#字符串去空格" class="headerlink" title="字符串去空格"></a>字符串去空格</h1><p>Java、C#和PHP等语言都实现了专门的字符串去空格函数，但JavaScript中是没有的，可以通过下面的代码来为String对象函数一个<strong>trim函数</strong>：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">String</span>.prototype.trim = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;<span class="keyword">return</span> <span class="keyword">this</span>.replace(<span class="regexp">/^\s+|\s+$/g</span>, <span class="string">""</span>);&#125;;</span><br></pre></td></tr></table></figure>
<p>新的JavaScript引擎已经有了trim()的原生实现</p>
<h1 id="数组之间追加"><a href="#数组之间追加" class="headerlink" title="数组之间追加"></a>数组之间追加</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> array1 = [<span class="number">12</span> , <span class="string">"foo"</span> , &#123;name <span class="string">"Joe"</span>&#125; , <span class="number">-2458</span>];</span><br><span class="line"><span class="keyword">var</span> array2 = [<span class="string">"Doe"</span> , <span class="number">555</span> , <span class="number">100</span>];</span><br><span class="line"><span class="built_in">Array</span>.prototype.push.apply(array1, array2);</span><br><span class="line"><span class="comment">/* array1 值为  [12 , "foo" , &#123;name "Joe"&#125; , -2458 , "Doe" , 555 , 100] */</span></span><br></pre></td></tr></table></figure>
<h1 id="对象转换为数组"><a href="#对象转换为数组" class="headerlink" title="对象转换为数组"></a>对象转换为数组</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> argArray = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>);</span><br></pre></td></tr></table></figure>
<h1 id="验证是否是数字"><a href="#验证是否是数字" class="headerlink" title="验证是否是数字"></a>验证是否是数字</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isNumber</span>(<span class="params">n</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> !<span class="built_in">isNaN</span>(<span class="built_in">parseFloat</span>(n)) &amp;&amp; <span class="built_in">isFinite</span>(n);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="验证是否是数组"><a href="#验证是否是数组" class="headerlink" title="验证是否是数组"></a>验证是否是数组</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isArray</span>(<span class="params">obj</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">Object</span>.prototype.toString.call(obj) === <span class="string">'[object Array]'</span> ;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>但如果toString()方法被重写过得话，就行不通了。也可以使用下面的方法：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.isArray(obj); <span class="comment">// its a new Array method</span></span><br></pre></td></tr></table></figure></p>
<p>如果在浏览器中没有使用frame，还可以用instanceof，但如果上下文太复杂，也有可能出错。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> myFrame = <span class="built_in">document</span>.createElement(<span class="string">'iframe'</span>);</span><br><span class="line"><span class="built_in">document</span>.body.appendChild(myFrame);</span><br><span class="line"><span class="keyword">var</span> myArray = <span class="built_in">window</span>.frames[<span class="built_in">window</span>.frames.length<span class="number">-1</span>].Array;</span><br><span class="line"><span class="keyword">var</span> arr = <span class="keyword">new</span> myArray(a,b,<span class="number">10</span>); <span class="comment">// [a,b,10]  </span></span><br><span class="line"><span class="comment">// myArray 的构造器已经丢失，instanceof 的结果将不正常</span></span><br><span class="line"><span class="comment">// 构造器是不能跨 frame 共享的</span></span><br><span class="line">arr <span class="keyword">instanceof</span> <span class="built_in">Array</span>; <span class="comment">// false</span></span><br></pre></td></tr></table></figure></p>
<h1 id="获取数组中的最大值和最小值"><a href="#获取数组中的最大值和最小值" class="headerlink" title="获取数组中的最大值和最小值"></a>获取数组中的最大值和最小值</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span>  numbers = [<span class="number">5</span>, <span class="number">458</span> , <span class="number">120</span> , <span class="number">-215</span> , <span class="number">228</span> , <span class="number">400</span> , <span class="number">122205</span>, <span class="number">-85411</span>]; </span><br><span class="line"><span class="keyword">var</span> maxInNumbers = <span class="built_in">Math</span>.max.apply(<span class="built_in">Math</span>, numbers); </span><br><span class="line"><span class="keyword">var</span> minInNumbers = <span class="built_in">Math</span>.min.apply(<span class="built_in">Math</span>, numbers);</span><br></pre></td></tr></table></figure>
<h1 id="清空数组"><a href="#清空数组" class="headerlink" title="清空数组"></a>清空数组</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> myArray = [<span class="number">12</span> , <span class="number">222</span> , <span class="number">1000</span> ];  </span><br><span class="line">myArray.length = <span class="number">0</span>; <span class="comment">// myArray will be equal to [].</span></span><br></pre></td></tr></table></figure>
<h1 id="不要直接从数组中delete或remove元素"><a href="#不要直接从数组中delete或remove元素" class="headerlink" title="不要直接从数组中delete或remove元素"></a>不要直接从数组中delete或remove元素</h1><p>如果对数组元素直接使用delete，其实并没有删除，只是将元素置为了undefined。数组元素删除应使用splice。</p>
<p>切忌：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> items = [<span class="number">12</span>, <span class="number">548</span> ,<span class="string">'a'</span> , <span class="number">2</span> , <span class="number">5478</span> , <span class="string">'foo'</span> , <span class="number">8852</span>, , <span class="string">'Doe'</span> ,<span class="number">2154</span> , <span class="number">119</span> ]; </span><br><span class="line">items.length; <span class="comment">// return 11 </span></span><br><span class="line"><span class="keyword">delete</span> items[<span class="number">3</span>]; <span class="comment">// return true </span></span><br><span class="line">items.length; <span class="comment">// return 11 </span></span><br><span class="line"><span class="comment">/* items 结果为 [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */</span></span><br></pre></td></tr></table></figure><br>而应：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> items = [<span class="number">12</span>, <span class="number">548</span> ,<span class="string">'a'</span> , <span class="number">2</span> , <span class="number">5478</span> , <span class="string">'foo'</span> , <span class="number">8852</span>, , <span class="string">'Doe'</span> ,<span class="number">2154</span> , <span class="number">119</span> ]; </span><br><span class="line">items.length; <span class="comment">// return 11 </span></span><br><span class="line">items.splice(<span class="number">3</span>,<span class="number">1</span>) ; </span><br><span class="line">items.length; <span class="comment">// return 10 </span></span><br><span class="line"><span class="comment">/* items 结果为 [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119]</span></span><br><span class="line"><span class="comment">删除对象的属性时可以使用delete。</span></span><br></pre></td></tr></table></figure></p>
<h1 id="使用length属性截断数组"><a href="#使用length属性截断数组" class="headerlink" title="使用length属性截断数组"></a>使用length属性截断数组</h1><p>前面的例子中用length属性清空数组，同样还可用它来截断数组<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> myArray = [<span class="number">12</span> , <span class="number">222</span> , <span class="number">1000</span> , <span class="number">124</span> , <span class="number">98</span> , <span class="number">10</span> ];  </span><br><span class="line">myArray.length = <span class="number">4</span>; <span class="comment">// myArray will be equal to [12 , 222 , 1000 , 124].</span></span><br></pre></td></tr></table></figure></p>
<p>与此同时，如果把length属性变大，数组的长度值变会增加，会使用undefined来作为新的元素填充。length是一个可写的属性。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">myArray.length = <span class="number">10</span>; <span class="comment">// the new array length is 10 </span></span><br><span class="line">myArray[myArray.length - <span class="number">1</span>] ; <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure></p>
<h1 id="在条件中使用逻辑与或"><a href="#在条件中使用逻辑与或" class="headerlink" title="在条件中使用逻辑与或"></a>在条件中使用逻辑与或</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> foo = <span class="number">10</span>;  </span><br><span class="line">foo == <span class="number">10</span> &amp;&amp; doSomething(); <span class="comment">// is the same thing as if (foo == 10) doSomething(); </span></span><br><span class="line">foo == <span class="number">5</span> || doSomething(); <span class="comment">// is the same thing as if (foo != 5) doSomething();</span></span><br></pre></td></tr></table></figure>
<p>逻辑或还可用来设置默认值，比如函数参数的默认值。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">doSomething</span>(<span class="params">arg1</span>)</span>&#123; </span><br><span class="line">    arg1 = arg1 || <span class="number">10</span>; <span class="comment">// arg1 will have 10 as a default value if it’s not already set</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="使得map-函数方法对数据循环"><a href="#使得map-函数方法对数据循环" class="headerlink" title="使得map()函数方法对数据循环"></a>使得map()函数方法对数据循环</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> squares = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>].map(<span class="function"><span class="keyword">function</span> (<span class="params">val</span>) </span>&#123;  </span><br><span class="line">    <span class="keyword">return</span> val * val;  </span><br><span class="line">&#125;); </span><br><span class="line"><span class="comment">// squares will be equal to [1, 4, 9, 16]</span></span><br></pre></td></tr></table></figure>
<h1 id="保留指定小数位数"><a href="#保留指定小数位数" class="headerlink" title="保留指定小数位数"></a>保留指定小数位数</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> num =<span class="number">2.443242342</span>;</span><br><span class="line">num = num.toFixed(<span class="number">4</span>);  <span class="comment">// num will be equal to 2.4432</span></span><br></pre></td></tr></table></figure>
<p>注意，toFixec()返回的是字符串，不是数字。</p>
<h1 id="浮点计算的问题"><a href="#浮点计算的问题" class="headerlink" title="浮点计算的问题"></a>浮点计算的问题</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">0.1</span> + <span class="number">0.2</span> === <span class="number">0.3</span> <span class="comment">// is false </span></span><br><span class="line"><span class="number">9007199254740992</span> + <span class="number">1</span> <span class="comment">// is equal to 9007199254740992</span></span><br><span class="line"><span class="number">9007199254740992</span> + <span class="number">2</span> <span class="comment">// is equal to 9007199254740994</span></span><br></pre></td></tr></table></figure>
<p>为什么呢？因为0.1+0.2等于0.30000000000000004。JavaScript的数字都遵循IEEE 754标准构建，在内部都是64位浮点小数表示，具体可以参见<a href="http://www.2ality.com/2012/04/number-encoding.html" target="_blank" rel="noopener">JavaScript中的数字是如何编码的</a>.</p>
<p>可以通过使用<strong>toFixed()</strong>和<strong>toPrecision()</strong>来解决这个问题</p>
<h1 id="通过for-in循环检查对象的属性"><a href="#通过for-in循环检查对象的属性" class="headerlink" title="通过for-in循环检查对象的属性"></a>通过for-in循环检查对象的属性</h1><p>下面这样的用法，可以防止迭代的时候进入到对象的原型属性中。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> name <span class="keyword">in</span> object) &#123;  </span><br><span class="line">    <span class="keyword">if</span> (object.hasOwnProperty(name)) &#123; </span><br><span class="line">        <span class="comment">// do something with name</span></span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="逗号操作符"><a href="#逗号操作符" class="headerlink" title="逗号操作符"></a>逗号操作符</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">0</span>; </span><br><span class="line"><span class="keyword">var</span> b = ( a++, <span class="number">99</span> ); </span><br><span class="line"><span class="built_in">console</span>.log(a);  <span class="comment">// a will be equal to 1 </span></span><br><span class="line"><span class="built_in">console</span>.log(b);  <span class="comment">// b is equal to 99</span></span><br></pre></td></tr></table></figure>
<h1 id="临时存储用于计算和查询的变量"><a href="#临时存储用于计算和查询的变量" class="headerlink" title="临时存储用于计算和查询的变量"></a>临时存储用于计算和查询的变量</h1><p>在jQuery选择器中，可以临时存储整个DOM元素<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> navright = <span class="built_in">document</span>.querySelector(<span class="string">'#right'</span>); </span><br><span class="line"><span class="keyword">var</span> navleft = <span class="built_in">document</span>.querySelector(<span class="string">'#left'</span>); </span><br><span class="line"><span class="keyword">var</span> navup = <span class="built_in">document</span>.querySelector(<span class="string">'#up'</span>); </span><br><span class="line"><span class="keyword">var</span> navdown = <span class="built_in">document</span>.querySelector(<span class="string">'#down'</span>);</span><br></pre></td></tr></table></figure></p>
<h1 id="提前检查传入-isFinite-的参数"><a href="#提前检查传入-isFinite-的参数" class="headerlink" title="提前检查传入 isFinite() 的参数"></a>提前检查传入 isFinite() 的参数</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">isFinite</span>(<span class="number">0</span>/<span class="number">0</span>) ; <span class="comment">// false</span></span><br><span class="line"><span class="built_in">isFinite</span>(<span class="string">"foo"</span>); <span class="comment">// false</span></span><br><span class="line"><span class="built_in">isFinite</span>(<span class="string">"10"</span>); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">isFinite</span>(<span class="number">10</span>);   <span class="comment">// true</span></span><br><span class="line"><span class="built_in">isFinite</span>(<span class="literal">undefined</span>);  <span class="comment">// false</span></span><br><span class="line"><span class="built_in">isFinite</span>();   <span class="comment">// false</span></span><br><span class="line"><span class="built_in">isFinite</span>(<span class="literal">null</span>);  <span class="comment">// true，这点当特别注意</span></span><br></pre></td></tr></table></figure>
<h1 id="避免在数组中使用负数做索引"><a href="#避免在数组中使用负数做索引" class="headerlink" title="避免在数组中使用负数做索引"></a>避免在数组中使用负数做索引</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> numbersArray = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>];</span><br><span class="line"><span class="keyword">var</span> <span class="keyword">from</span> = numbersArray.indexOf(<span class="string">"foo"</span>) ;  <span class="comment">// from is equal to -1</span></span><br><span class="line">numbersArray.splice(<span class="keyword">from</span>,<span class="number">2</span>);    <span class="comment">// will return [5]</span></span><br></pre></td></tr></table></figure>
<p>注意传给splice的索引参数不要是负数，当是负数时，会从数组结尾处删除元素。</p>
<h1 id="用JSON来序列化与反序列化"><a href="#用JSON来序列化与反序列化" class="headerlink" title="用JSON来序列化与反序列化"></a>用JSON来序列化与反序列化</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> person = &#123;<span class="attr">name</span> :<span class="string">'Saad'</span>, <span class="attr">age</span> : <span class="number">26</span>, <span class="attr">department</span> : &#123;<span class="attr">ID</span> : <span class="number">15</span>, <span class="attr">name</span> : <span class="string">"R&amp;D"</span>&#125; &#125;;</span><br><span class="line"><span class="keyword">var</span> stringFromPerson = <span class="built_in">JSON</span>.stringify(person);</span><br><span class="line"><span class="comment">/* stringFromPerson 结果为 "&#123;"name":"Saad","age":26,"department":&#123;"ID":15,"name":"R&amp;D"&#125;&#125;"   */</span></span><br><span class="line"><span class="keyword">var</span> personFromString = <span class="built_in">JSON</span>.parse(stringFromPerson);</span><br><span class="line"><span class="comment">/* personFromString 的值与 person 对象相同  */</span></span><br></pre></td></tr></table></figure>
<h1 id="不要使用eval-或者函数构造器"><a href="#不要使用eval-或者函数构造器" class="headerlink" title="不要使用eval()或者函数构造器"></a>不要使用eval()或者函数构造器</h1><p>eval()和函数构造器（Function consturctor）的开销较大，每次调用，JavaScript引擎都要将源代码转换为可执行的代码。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> func1 = <span class="keyword">new</span> <span class="built_in">Function</span>(functionCode);</span><br><span class="line"><span class="keyword">var</span> func2 = <span class="built_in">eval</span>(functionCode);</span><br></pre></td></tr></table></figure></p>
<h1 id="避免使用with"><a href="#避免使用with" class="headerlink" title="避免使用with()"></a>避免使用with()</h1><p>使用with()可以把变量加入到全局作用域中，因此，如果有其它的同名变量，一来容易混淆，二来值也会被覆盖</p>
<h1 id="不要对数组使用for-in"><a href="#不要对数组使用for-in" class="headerlink" title="不要对数组使用for-in"></a>不要对数组使用for-in</h1><p>避免：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> sum = <span class="number">0</span>;  </span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> arrayNumbers) &#123;  </span><br><span class="line">    sum += arrayNumbers[i];  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br>而是:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> sum = <span class="number">0</span>;  </span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, len = arrayNumbers.length; i &lt; len; i++) &#123;  </span><br><span class="line">    sum += arrayNumbers[i];  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br>另外一个好处是，i和len两个变量是在for循环的第一个声明中，二者只会初始化一次，这要比下面这种写法快：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; arrayNumbers.length; i++)</span><br></pre></td></tr></table></figure>
<h1 id="传给setInterval-和setTimeout-时使用函数而不是字符串"><a href="#传给setInterval-和setTimeout-时使用函数而不是字符串" class="headerlink" title="传给setInterval()和setTimeout()时使用函数而不是字符串"></a>传给setInterval()和setTimeout()时使用函数而不是字符串</h1><p>如果传给setTimeout()和setInterval()一个字符串，他们将会用类似于eval方式进行转换，这肯定会要慢些，因此不要使用：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">setInterval(<span class="string">'doSomethingPeriodically()'</span>, <span class="number">1000</span>);  </span><br><span class="line">setTimeout(<span class="string">'doSomethingAfterFiveSeconds()'</span>, <span class="number">5000</span>);</span><br></pre></td></tr></table></figure><br>而是用：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">setInterval(doSomethingPeriodically, <span class="number">1000</span>);  </span><br><span class="line">setTimeout(doSomethingAfterFiveSeconds, <span class="number">5000</span>);</span><br></pre></td></tr></table></figure></p>
<h1 id="使用switch-case代替一大叠的if-else"><a href="#使用switch-case代替一大叠的if-else" class="headerlink" title="使用switch/case代替一大叠的if/else"></a>使用switch/case代替一大叠的if/else</h1><p>当判断有超过两个分支的时候使用switch/case要更快一些，而且也更优雅，更利于代码的组织，当然，如果有超过10个分支，就不要使用switch/case了。</p>
<h1 id="在switch-case中使用数字区间"><a href="#在switch-case中使用数字区间" class="headerlink" title="在switch/case中使用数字区间"></a>在switch/case中使用数字区间</h1><p>其实，switch/case中的case条件，还可以这样写：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getCategory</span>(<span class="params">age</span>) </span>&#123;  </span><br><span class="line">    <span class="keyword">var</span> category = <span class="string">""</span>;  </span><br><span class="line">    <span class="keyword">switch</span> (<span class="literal">true</span>) &#123;  </span><br><span class="line">        <span class="keyword">case</span> <span class="built_in">isNaN</span>(age):  </span><br><span class="line">            category = <span class="string">"not an age"</span>;  </span><br><span class="line">            <span class="keyword">break</span>;  </span><br><span class="line">        <span class="keyword">case</span> (age &gt;= <span class="number">50</span>):  </span><br><span class="line">            category = <span class="string">"Old"</span>;  </span><br><span class="line">            <span class="keyword">break</span>;  </span><br><span class="line">        <span class="keyword">case</span> (age &lt;= <span class="number">20</span>):  </span><br><span class="line">            category = <span class="string">"Baby"</span>;  </span><br><span class="line">            <span class="keyword">break</span>;  </span><br><span class="line">        <span class="keyword">default</span>:  </span><br><span class="line">            category = <span class="string">"Young"</span>;  </span><br><span class="line">            <span class="keyword">break</span>;  </span><br><span class="line">    &#125;;  </span><br><span class="line">    <span class="keyword">return</span> category;  </span><br><span class="line">&#125;  </span><br><span class="line">getCategory(<span class="number">5</span>);  <span class="comment">// 将返回 "Baby"</span></span><br></pre></td></tr></table></figure></p>
<h1 id="使用对象作为对象的原型"><a href="#使用对象作为对象的原型" class="headerlink" title="使用对象作为对象的原型"></a>使用对象作为对象的原型</h1><p>下面这样，便可以给定对象作为参数，来创建以此为原型的新对象：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">clone</span>(<span class="params">object</span>) </span>&#123;  </span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">OneShotConstructor</span>(<span class="params"></span>)</span>&#123;&#125;; </span><br><span class="line">    OneShotConstructor.prototype = object;  </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> OneShotConstructor(); </span><br><span class="line">&#125; </span><br><span class="line">clone(<span class="built_in">Array</span>).prototype ;  <span class="comment">// []</span></span><br></pre></td></tr></table></figure></p>
<h1 id="HTML字段转换函数"><a href="#HTML字段转换函数" class="headerlink" title="HTML字段转换函数"></a>HTML字段转换函数</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">escapeHTML</span>(<span class="params">text</span>) </span>&#123;  </span><br><span class="line">    <span class="keyword">var</span> replacements= &#123;<span class="string">"&lt;"</span>: <span class="string">"&amp;lt;"</span>, <span class="string">"&gt;"</span>: <span class="string">"&amp;gt;"</span>,<span class="string">"&amp;"</span>: <span class="string">"&amp;amp;"</span>, <span class="string">"\""</span>: <span class="string">"&amp;quot;"</span>&#125;;                      </span><br><span class="line">    <span class="keyword">return</span> text.replace(<span class="regexp">/[&lt;&gt;&amp;"]/g</span>, <span class="function"><span class="keyword">function</span>(<span class="params">character</span>) </span>&#123;  </span><br><span class="line">        <span class="keyword">return</span> replacements[character];  </span><br><span class="line">    &#125;); </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="不要在循环内部使用try-catch-finally"><a href="#不要在循环内部使用try-catch-finally" class="headerlink" title="不要在循环内部使用try-catch-finally"></a>不要在循环内部使用try-catch-finally</h1><p>try-catch-finally中catch部分在执行时会将异常赋给一个变量，这个变量会被构建成一个运行时作用域内的新的变量。<br>切忌：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> object = [<span class="string">'foo'</span>, <span class="string">'bar'</span>], i;  </span><br><span class="line"><span class="keyword">for</span> (i = <span class="number">0</span>, len = object.length; i &lt;len; i++) &#123;  </span><br><span class="line">    <span class="keyword">try</span> &#123;  </span><br><span class="line">        <span class="comment">// do something that throws an exception </span></span><br><span class="line">    &#125;  </span><br><span class="line">    <span class="keyword">catch</span> (e) &#123;   </span><br><span class="line">        <span class="comment">// handle exception  </span></span><br><span class="line">    &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br>而应该：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> object = [<span class="string">'foo'</span>, <span class="string">'bar'</span>], i;  </span><br><span class="line"><span class="keyword">try</span> &#123; </span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>, len = object.length; i &lt;len; i++) &#123;  </span><br><span class="line">        <span class="comment">// do something that throws an exception </span></span><br><span class="line">    &#125; </span><br><span class="line">&#125; </span><br><span class="line"><span class="keyword">catch</span> (e) &#123;   </span><br><span class="line">    <span class="comment">// handle exception  </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h1 id="使用XMLHttpRequests时注意设置超时"><a href="#使用XMLHttpRequests时注意设置超时" class="headerlink" title="使用XMLHttpRequests时注意设置超时"></a>使用XMLHttpRequests时注意设置超时</h1><p>XMLHttpRequests在执行时，当长时间没有响应（如出现网络问题等）时，应该中止掉连接，可以通过setTimeout()来完成这个工作：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest (); </span><br><span class="line">xhr.onreadystatechange = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;  </span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.readyState == <span class="number">4</span>) &#123;  </span><br><span class="line">        clearTimeout(timeout);  </span><br><span class="line">        <span class="comment">// do something with response data </span></span><br><span class="line">    &#125;  </span><br><span class="line">&#125;  </span><br><span class="line"><span class="keyword">var</span> timeout = setTimeout( <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;  </span><br><span class="line">    xhr.abort(); <span class="comment">// call error callback  </span></span><br><span class="line">&#125;, <span class="number">60</span>*<span class="number">1000</span> <span class="comment">/* timeout after a minute */</span> ); </span><br><span class="line">xhr.open(<span class="string">'GET'</span>, url, <span class="literal">true</span>);  </span><br><span class="line">xhr.send();</span><br></pre></td></tr></table></figure><br>同时需要注意的是，不要同时发起多个XMLHttpRequests请求。</p>
<h1 id="处理WebSocket的超时"><a href="#处理WebSocket的超时" class="headerlink" title="处理WebSocket的超时"></a>处理WebSocket的超时</h1><p>通常情况下，WebSocket连接创建后，如果30秒内没有任何活动，服务器端会对连接进行超时处理，防火墙也可以对单位周期没有活动的连接进行超时处理。</p>
<p>为了防止这种情况的发生，可以每隔一定时间，往服务器发送一条空的消息。可以通过下面这两个函数来实现这个需求，一个用于使连接保持活动状态，另一个专门用于结束这个状态。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> timerID = <span class="number">0</span>; </span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">keepAlive</span>(<span class="params"></span>) </span>&#123; </span><br><span class="line">    <span class="keyword">var</span> timeout = <span class="number">15000</span>;  </span><br><span class="line">    <span class="keyword">if</span> (webSocket.readyState == webSocket.OPEN) &#123;  </span><br><span class="line">        webSocket.send(<span class="string">''</span>);  </span><br><span class="line">    &#125;  </span><br><span class="line">    timerId = setTimeout(keepAlive, timeout);  </span><br><span class="line">&#125;  </span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">cancelKeepAlive</span>(<span class="params"></span>) </span>&#123;  </span><br><span class="line">    <span class="keyword">if</span> (timerId) &#123;  </span><br><span class="line">        cancelTimeout(timerId);  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br>keepAlive()函数可以放在WebSocket连接的onOpen()方法的最后面，cancelKeepAlive()放在onClose()方法的最末尾</p>
<h1 id="时间注意原始操作符比函数调用快，使用VanillaJS"><a href="#时间注意原始操作符比函数调用快，使用VanillaJS" class="headerlink" title="时间注意原始操作符比函数调用快，使用VanillaJS"></a>时间注意<a href="https://dev.opera.com/articles/efficient-javascript/?page=2#primitiveoperator" target="_blank" rel="noopener">原始操作符比函数调用快</a>，使用<a href="http://vanilla-js.com/" target="_blank" rel="noopener">VanillaJS</a></h1><p>比如，一般不要这样：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> min = <span class="built_in">Math</span>.min(a,b); </span><br><span class="line">A.push(v);</span><br></pre></td></tr></table></figure></p>
<p>可以这样来代替：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> min = a &lt; b ? a : b; </span><br><span class="line">A[A.length] = v;</span><br></pre></td></tr></table></figure></p>
<h1 id="开发时注意代码结构，上线前检查并压缩JavaScript代码"><a href="#开发时注意代码结构，上线前检查并压缩JavaScript代码" class="headerlink" title="开发时注意代码结构，上线前检查并压缩JavaScript代码"></a>开发时注意代码结构，上线前检查并压缩JavaScript代码</h1><p>可以使用JSLint或JSMin等工具来检查并压缩代码。</p>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#首次为变量赋值时务必使用var关键字"><span class="toc-number">1.</span> <span class="toc-text">首次为变量赋值时务必使用var关键字</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#使用-取代"><span class="toc-number">2.</span> <span class="toc-text">使用&#x3D;&#x3D;&#x3D;取代&#x3D;&#x3D;</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#underfined、null、0、false、NaN、空字符串的逻辑结果均为false"><span class="toc-number">3.</span> <span class="toc-text">underfined、null、0、false、NaN、空字符串的逻辑结果均为false</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#行尾使用分号"><span class="toc-number">4.</span> <span class="toc-text">行尾使用分号</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#使用对象构造器"><span class="toc-number">5.</span> <span class="toc-text">使用对象构造器</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#小心使用typeof、instanceof和contructor"><span class="toc-number">6.</span> <span class="toc-text">小心使用typeof、instanceof和contructor</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#使用自调用函数"><span class="toc-number">7.</span> <span class="toc-text">使用自调用函数</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#从数组中随机获取成员"><span class="toc-number">8.</span> <span class="toc-text">从数组中随机获取成员</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#获取指定范围内的随机数"><span class="toc-number">9.</span> <span class="toc-text">获取指定范围内的随机数</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#生成从0到指定值的数字数组"><span class="toc-number">10.</span> <span class="toc-text">生成从0到指定值的数字数组</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#生成随机的字母数字字符串"><span class="toc-number">11.</span> <span class="toc-text">生成随机的字母数字字符串</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#打乱数字数组的顺序"><span class="toc-number">12.</span> <span class="toc-text">打乱数字数组的顺序</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#字符串去空格"><span class="toc-number">13.</span> <span class="toc-text">字符串去空格</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#数组之间追加"><span class="toc-number">14.</span> <span class="toc-text">数组之间追加</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#对象转换为数组"><span class="toc-number">15.</span> <span class="toc-text">对象转换为数组</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#验证是否是数字"><span class="toc-number">16.</span> <span class="toc-text">验证是否是数字</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#验证是否是数组"><span class="toc-number">17.</span> <span class="toc-text">验证是否是数组</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#获取数组中的最大值和最小值"><span class="toc-number">18.</span> <span class="toc-text">获取数组中的最大值和最小值</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#清空数组"><span class="toc-number">19.</span> <span class="toc-text">清空数组</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#不要直接从数组中delete或remove元素"><span class="toc-number">20.</span> <span class="toc-text">不要直接从数组中delete或remove元素</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#使用length属性截断数组"><span class="toc-number">21.</span> <span class="toc-text">使用length属性截断数组</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#在条件中使用逻辑与或"><span class="toc-number">22.</span> <span class="toc-text">在条件中使用逻辑与或</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#使得map-函数方法对数据循环"><span class="toc-number">23.</span> <span class="toc-text">使得map()函数方法对数据循环</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#保留指定小数位数"><span class="toc-number">24.</span> <span class="toc-text">保留指定小数位数</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#浮点计算的问题"><span class="toc-number">25.</span> <span class="toc-text">浮点计算的问题</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#通过for-in循环检查对象的属性"><span class="toc-number">26.</span> <span class="toc-text">通过for-in循环检查对象的属性</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#逗号操作符"><span class="toc-number">27.</span> <span class="toc-text">逗号操作符</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#临时存储用于计算和查询的变量"><span class="toc-number">28.</span> <span class="toc-text">临时存储用于计算和查询的变量</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#提前检查传入-isFinite-的参数"><span class="toc-number">29.</span> <span class="toc-text">提前检查传入 isFinite() 的参数</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#避免在数组中使用负数做索引"><span class="toc-number">30.</span> <span class="toc-text">避免在数组中使用负数做索引</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#用JSON来序列化与反序列化"><span class="toc-number">31.</span> <span class="toc-text">用JSON来序列化与反序列化</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#不要使用eval-或者函数构造器"><span class="toc-number">32.</span> <span class="toc-text">不要使用eval()或者函数构造器</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#避免使用with"><span class="toc-number">33.</span> <span class="toc-text">避免使用with()</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#不要对数组使用for-in"><span class="toc-number">34.</span> <span class="toc-text">不要对数组使用for-in</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#传给setInterval-和setTimeout-时使用函数而不是字符串"><span class="toc-number">35.</span> <span class="toc-text">传给setInterval()和setTimeout()时使用函数而不是字符串</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#使用switch-case代替一大叠的if-else"><span class="toc-number">36.</span> <span class="toc-text">使用switch&#x2F;case代替一大叠的if&#x2F;else</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#在switch-case中使用数字区间"><span class="toc-number">37.</span> <span class="toc-text">在switch&#x2F;case中使用数字区间</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#使用对象作为对象的原型"><span class="toc-number">38.</span> <span class="toc-text">使用对象作为对象的原型</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#HTML字段转换函数"><span class="toc-number">39.</span> <span class="toc-text">HTML字段转换函数</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#不要在循环内部使用try-catch-finally"><span class="toc-number">40.</span> <span class="toc-text">不要在循环内部使用try-catch-finally</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#使用XMLHttpRequests时注意设置超时"><span class="toc-number">41.</span> <span class="toc-text">使用XMLHttpRequests时注意设置超时</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#处理WebSocket的超时"><span class="toc-number">42.</span> <span class="toc-text">处理WebSocket的超时</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#时间注意原始操作符比函数调用快，使用VanillaJS"><span class="toc-number">43.</span> <span class="toc-text">时间注意原始操作符比函数调用快，使用VanillaJS</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#开发时注意代码结构，上线前检查并压缩JavaScript代码"><span class="toc-number">44.</span> <span class="toc-text">开发时注意代码结构，上线前检查并压缩JavaScript代码</span></a></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
